package com.ruike.alisurface.ui.payPage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.CardTopUpBean;
import com.ruike.alisurface.bean.OrderrBean;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.ui.mainPage.MainActivity;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.NumberUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ZXingUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: voodoo
 * CreateDate: 2020-04-08
 * Description: 扫码页
 */
public class PayForQRCodeActivity extends BaseAty {

    @BindView(R.id.titleBar_titleIco_imgv)
    ImageView titleBarTitleIcoImgv;
    @BindView(R.id.titleBar_appVersion_tv)
    TextView titleBarAppVersionTv;
    @BindView(R.id.titleBar_sn_tv)
    TextView titleBarSnTv;
    @BindView(R.id.titleBar_setting_view)
    View titleBarSettingView;
    @BindView(R.id.titleBar_root_rlayout)
    RelativeLayout titleBarRootRlayout;

    @BindView(R.id.alchatPay_goback_imgv)
    ImageView alchatPayGobackImgv;
    @BindView(R.id.alchat_tuijian)
    TextView alchatTuijian;
    @BindView(R.id.alchat_zxing_code)
    ImageView alchatZxingCode;
    @BindView(R.id.alchat_zxing_price)
    TextView aliZxingPrice;
    @BindView(R.id.alchat_zxing_count_time)
    TextView aliZxingCountTime;

    String OrderNO;
    Bitmap bitmap;
    Timer paytimer = new Timer();
    TimerTask timerTask;

    @BindView(R.id.pay_type_yhmj)
    TextView payTypeYhmj;
    @BindView(R.id.pay_type_yhljm)
    TextView payTypeYhljm;
    @BindView(R.id.pay_type_mjyh)
    RelativeLayout payTypeMjyh;
    @BindView(R.id.pay_type_zklv)
    TextView payTypeZklv;
    @BindView(R.id.pay_type_zkyh)
    RelativeLayout payTypeZkyh;
    @BindView(R.id.alchat_yj)
    TextView alchatYj;
    @BindView(R.id.alchat_yyhje)
    TextView alchatYyhje;
    @BindView(R.id.alchat_yyh_payje)
    TextView alchatYyhPayje;
    @BindView(R.id.pay_type_moryh)
    RelativeLayout payTypeMoryh;
    @BindView(R.id.layout_yhhd)
    LinearLayout layoutYhhd;

    @BindView(R.id.view_zw_hdie)
    View vhide;

    // 卡充值扫码
    private boolean isTopCarPay = false;
    private CardTopUpBean cardTopUpBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_wealchat;
    }

    @Override
    protected void initViews() {
        L.i("扫码支付页==" + this.getClass().getName());
        initTitleBar(false);

    }

    List<CarGoodsBeans> paycarlist;
    double monry = 0.0f;

    @Override
    protected void initData() {

        // 20200703 卡充值的时候传入数据，直接处理卡充值的数据
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            isTopCarPay = bundle.getBoolean("isTopCarPay", true);
            cardTopUpBean = (CardTopUpBean) bundle.getSerializable("cardTopUpBean");
            OrderNO = cardTopUpBean.getData().getOrder().getOrderNo();
            aliZxingPrice.setText(new StringBuffer("总金额：").append(cardTopUpBean.getData().getOrder().getTotal_fee()).toString());
            bitmap = ZXingUtils.createQRImage((cardTopUpBean.getData().getUrl()), 500, 500, BitmapFactory.decodeResource(getResources(), 0));
            alchatZxingCode.setImageBitmap(bitmap);

            if (timerTask != null) {
                timerTask.cancel();
            }
            if (!BuildConfig.DEBUG) {
                timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        MchApiHttp.getPayResult(PayForQRCodeActivity.this, OrderNO);
                    }
                };
                paytimer.schedule(timerTask, 10, 3000);
            } else {
                new MyCountDownTimer(5000, 5000) {

                    @Override
                    public void onTick(long millisUntilFinished) {

                    }

                    @Override
                    public void onFinish() {
                        Bundle bundle = new Bundle();
                        bundle.putString("resultStr", new StringBuffer("充值成功\n\n\r").append("卡：123456789 在机器：qwertyuiop 上充值了好几兆亿，你真范老师").toString());
                        startActivity(TopUpResultActivity.class, bundle);
                    }
                }.start();
            }
            return;
        }

        paycarlist = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        SystemClock.sleep(500);
        if (paycarlist == null) {
            L.i("查询商品数据异常");
            return;
        }

        for (int i = 0; i < paycarlist.size(); i++) {
            Double dd = new Double(paycarlist.get(i).getPrice());
            if (dd > 0) {
                monry += paycarlist.get(i).getPrice();
            }
        }
        L.i("paycarlist====" + paycarlist.toString());
        aliZxingPrice.setText(new StringBuffer("总金额：").append(monry).toString());

        showcodeAlt();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(120, aliZxingCountTime, isTopCarPay ? null : SelectPayTypeActivity.class);
    }

    OrderrBean orderrBean;
    ShopDetailBean shopDetailBean;

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        L.i("requestUrl==" + requestUrl);
        if (requestUrl.endsWith("create") || requestUrl.endsWith("CreateForProduct")) {
            // 获取商品支付信息
            orderrBean = GsonUtils.json2Model(requestJsonStr, OrderrBean.class);
            String zxinurl = orderrBean.getData().getUrl();
            OrderNO = orderrBean.getData().getOrder().getOrderNo();
            bitmap = ZXingUtils.createQRImage((zxinurl), 500, 500, BitmapFactory.decodeResource(getResources(), 0));
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            alchatZxingCode.setImageBitmap(bitmap);

            startCountdownTimer(120, aliZxingCountTime, SelectPayTypeActivity.class);

            shopDetailBean = new ShopDetailBean(OrderNO);
            shopDetailBean.setPromotion_fee(orderrBean.getData().getOrder().getPromotion_fee());
            shopDetailBean.setTotal_fee(orderrBean.getData().getOrder().getTotal_fee());
            shopDetailBean.setPay_fee(orderrBean.getData().getOrder().getPay_fee());
            L.i("shopDetailBean", shopDetailBean.toString());

            shopDetailBean.setDetailOrderList(orderrBean.getData().getOrder().getOrderDetails());

            try {
                if (timerTask != null) {
                    timerTask.cancel();
                }
                timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        MchApiHttp.getPayResult(PayForQRCodeActivity.this, OrderNO);
                    }
                };
                paytimer.schedule(timerTask, 10, 3000);

                String acty_config = orderrBean.getData().getOrder().getActivity_config();
                String acty_id = orderrBean.getData().getOrder().getActivity_id();

                setHuoDongoing(acty_config, acty_id);
                L.i("acty_id=acty_config===", ShareUtils.getInstance().getString(ShareKey.ACTIVITY_ID, "0"));
            } catch (JSONException e) {
                L.i("wechar===", e.getMessage());
            }

        } else if (requestUrl.endsWith("CreateForProduct")) {


        } else if (requestUrl.endsWith("getPayResult")) {
            JSONObject object = null;
            try {

                object = new JSONObject(requestJsonStr);
                int code = object.optInt("code");
                L.i("getPayResult==" + requestJsonStr);
                if (code == 0) {
                    setCanal();
                    if (isTopCarPay) {
                        Bundle bundle = new Bundle();
                        bundle.putString("resultStr", new StringBuffer("充值成功\n\r").append(cardTopUpBean.getData().getOrder().getDetails()).toString());
                        startActivity(TopUpResultActivity.class, bundle);
//                        new CustomDialog.Builder(PayForQRCodeActivity.this)
//                                .setMessage(new StringBuffer("充值成功\n\r").append(cardTopUpBean.getData().getOrder().getDetails()).toString())
//                                .setTitle("充值结果")
//                                .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        // 直接退出到主界面（广告或者商品展示界面）
//                                        startCountdownTimer(0, null, null);
//                                        finish();
//                                    }
//                                }).create().show();
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString("pay_type", "wechat");
                        bundle.putSerializable("orderrBeanData", shopDetailBean);
                        startActivity(PayShowShopActivity.class, bundle);
                        finish();
                    }
                } else {
                    L.i("getPayResult" + "==等待支付=");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("getPayResult")) {
            L.e(requestUrl + "==onError=" + errorMsg, "---等待支付--");
//            setCanal();
//
//            Bundle bundle = new Bundle();
//            bundle.putString("pay_type", "wechat");
//            bundle.putSerializable("orderrBeanData", shopDetailBean);
//            startActivity(PayShowShopActivity.class, bundle);
//            finish();
        } else if (requestUrl.endsWith("create")) {
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            L.e(requestUrl + "=onError==" + errorMsg);
            showErrorTip(errorMsg);

        } else if (requestUrl.endsWith("CreateForProduct")) {
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            L.e(requestUrl + "=onError==" + errorMsg);
            showErrorTip(errorMsg);
        }
    }

    @OnClick({R.id.alchatPay_goback_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.alchatPay_goback_imgv:
                String tip = "支付过程中请勿关闭该扫码支付页面，否则即使支付成功也无法出货！！！\r\n\r\n" +
                        "如想返回其它页面则点击确认，否则点击取消等待支付完成后出货！！！";
                gobackTip(tip, SelectPayTypeActivity.class);
                break;
        }
    }

    CustomDialog dialog;

    public void gobackTip(String tip, Class<?> cls) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new CustomDialog.Builder(this).setTitle("温馨提示")
                .setMessage(tip).setTouchOutsideCloseDialog(false)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (isTopCarPay) {
                            startCountdownTimer(0, null, null);
                        } else {
                            startActivity(cls, null);
                            finish();
                        }
                    }
                }).setNegativeButton("取消", null).create();
        dialog.show();
    }

    AlertDialog alertDialog;

    /**
     * 生成二维码提示框
     */
    private void showcodeAlt() {
        try {
            showProgressDialog("正在生成二维码加载数据，请稍后......", false);
            if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 1) == 1) {
                L.i("按货道展示上传信息");
                getPayinfoCode();
            } else {
                L.i("按商品类型展示上传信息");
                getPayTypeinfoCode();
            }
        } catch (Exception e) {
            L.i("pay====error==", e.getLocalizedMessage());
        }
    }

    public void getPayinfoCode() {
        try {
            //判断数据是否已经存在
            String result = "";
            for (int i = 0; i < paycarlist.size(); i++) {
                result += paycarlist.get(i).getSlotIndexs() + ",";
            }
            Map<String, Integer> map;
            List list1 = new ArrayList();
            //将字符串转化为字符数组
            String[] chars = result.split(",");
            //创建一个HashMap名为hm
            HashMap<String, Integer> hm = new HashMap();
            //定义一个字符串c，循环遍历遍历chars数组
            for (String c : chars) {
                if (!hm.containsKey(c)) {
                    hm.put(c, 1);
                } else {
                    //否则获得c的值并且加1
                    hm.put(c, hm.get(c) + 1);
                }
                //或者上面的if和else替换成下面这一行
                /*  hm.put(c,hm.containsKey(c) ? hm.get(c)+1:1);*/
            }
            //上传商品详情 去的订单号 显示成二维码
            for (String key : hm.keySet()) {
                map = new HashMap<>();
                //hm.keySet()代表所有键的集合,进行格式化输出
                map.put("Quantity", hm.get(key));
                map.put("SlotIndex", Integer.parseInt(String.valueOf(key)));
                list1.add(map);
            }

            HashMap<String, Object> maps = new HashMap<>();
            maps.put("mchId", ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
            maps.put("OrderDetails", GsonUtils.list2JsonArrayNotNulls(list1));
            maps.put("IsFace", false);
            MchApiHttp.postGoodsQRCode(this, maps);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void getPayTypeinfoCode() {
        try {
            //判断数据是否已经存在
            Map<String, Object> map;
            List list1 = new ArrayList();
            //上传商品详情 去的订单号 显示成二维码
            for (int i = 0; i < paycarlist.size(); i++) {
                map = new HashMap<>();
                map.put("Quantity", 1);
                map.put("productid", paycarlist.get(i).getProductid());
                List<Integer> slotIndexs = new ArrayList<>();
                L.i("slotIndexs====", paycarlist.get(i).getSlotIndexs());
                JSONArray jsonArray = new JSONArray(paycarlist.get(i).getSlotIndexs());
                for (int c = 0; c < jsonArray.length(); c++) {
                    slotIndexs.add(Integer.parseInt(jsonArray.opt(c) + ""));
                }
                map.put("slotIndexs", slotIndexs);
                list1.add(map);
            }
            HashMap<String, Object> maps = new HashMap<>();
            maps.put("mchid", ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
            maps.put("OrderDetails", GsonUtils.list2JsonArrayNotNulls(list1));
            MchApiHttp.postGoodsTypeQRCode(this, maps);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void setCanal() {
        if (paytimer != null) {
            L.i("==setCanal==" + paytimer);
            paytimer.cancel();
            paytimer = null;
        }

        if (timerTask != null) {
            L.i("==setCanal==" + timerTask);
            timerTask.cancel();
            timerTask = null;
        }

    }

    /**
     * 活动显示数据判断
     */
    public void setHuoDongoing(String acty_config, String acty_id) throws JSONException {
        if (TextUtils.isEmpty(acty_id)) {
            ShareUtils.getInstance().putString(ShareKey.ACTIVITY_ID, "0");
            return;
        }
        L.i("acty_id=acty_config====", orderrBean.getData().getOrder().getActivity_id());
        if (orderrBean.getData().getOrder().getActivity_id().equals("1")) { // 转盘
            vhide.setVisibility(View.VISIBLE);
            layoutYhhd.setVisibility(View.GONE);
            ShareUtils.getInstance().putString(ShareKey.ACTIVITY_ID, "1");
            return;
        }
        JSONObject Js = new JSONObject(acty_config);
        if (TextUtils.isEmpty(acty_config)) {
            return;
        }
        if (orderrBean.getData().getOrder().getActivity_id().equals("2")) { //满减
            layoutYhhd.setVisibility(View.VISIBLE);
            vhide.setVisibility(View.GONE);
            payTypeMjyh.setVisibility(View.VISIBLE);
            payTypeZkyh.setVisibility(View.GONE);

            String full = Js.optString("full", "");
            String reduce = Js.optString("reduce", "");
            payTypeYhmj.setText(full + "");
            payTypeYhljm.setText(reduce + "");
            if (Double.valueOf(full) <= monry) {
                alchatYj.setText(monry + "");
                alchatYyhje.setText(reduce + "");
                Double payjine = NumberUtils.round(monry - Double.valueOf(reduce), 2);
                alchatYyhPayje.setText(payjine + "");
                aliZxingPrice.setText("总金额：" + alchatYyhPayje.getText() + "");
            }
            ShareUtils.getInstance().putString(ShareKey.ACTIVITY_ID, "2");
            return;
        }
        if (orderrBean.getData().getOrder().getActivity_id().equals("3")) { //折扣
            layoutYhhd.setVisibility(View.VISIBLE);
            vhide.setVisibility(View.GONE);
            payTypeZkyh.setVisibility(View.VISIBLE);
            payTypeMjyh.setVisibility(View.GONE);
            String off_rate = Js.optString("off_rate", "0");
            int zhek = Double.valueOf(off_rate).intValue();
            payTypeZklv.setText(zhek + "");
            Double payje = monry * (1 - (zhek / 100)) == 0 ? 0.01 : monry * (1 - (zhek / 100));
            Double yhje = monry - payje;
            Double payjine = NumberUtils.round(payje, 2);
            alchatYj.setText(monry + "");
            alchatYyhje.setText(yhje + "");
            alchatYyhPayje.setText(payjine + "");
            ShareUtils.getInstance().putString(ShareKey.ACTIVITY_ID, "3");

            aliZxingPrice.setText("总金额：" + alchatYyhPayje.getText() + "");
            return;
        }

    }

    @Override
    public void doEventBusResult(MsgEventBus event) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.i("==onDestroy==");
        if (dialog != null && dialog.isShowing()) {
            dialog.cancel();
            dialog = null;
        }
        setCanal();

        if (bitmap != null) {

            alchatZxingCode.setImageBitmap(null);
            bitmap.recycle();
            bitmap = null;
        }

        if (alertDialog != null) {
            alertDialog.dismiss();
            alertDialog = null;
        }
    }


}
